package com.gss.plugin.oauth2.service.impl;

import com.gss.datasource.mapper.sys.SysRoleMapper;
import com.gss.entity.sys.dto.SysMenu;
import com.gss.plugin.oauth2.config.Oauth2Properties;
import com.gss.plugin.oauth2.service.ICustomAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

/**
 * @author DYang
 * @date 2023/8/20
 */
@Service
public class CustomAuthServiceImpl implements ICustomAuthService {

    @Autowired
    private Oauth2Properties oAuth2Properties;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        String uri = request.getRequestURI();
        //获取权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (authorities.contains(new SimpleGrantedAuthority("super"))) {
            return true;
        }
        // 解析授权，去数据库中查询是否拥有权限
        for (GrantedAuthority authority : authorities) {
            String role = authority.getAuthority();
            if (role.contains("[") || role.contains("]")) {
                continue;
            }
            List<SysMenu> menuList = sysRoleMapper.getResourceByRoleCode(role);
            if (menuList == null || menuList.size() == 0) {
                continue;
            }
            // 判断请求资源是否授权
            for (SysMenu sysMenu : menuList) {
                if (sysMenu.getUrl().equals(uri)) {
                    return true;
                }
            }
        }

        //判断授权
//        return authorities.contains(new SimpleGrantedAuthority(uri));
        // 无访问权限
        return false;
    }

}
